//
//  SN_PersonalInfo_ViewController.m
//  Shiyun_Newspaper
//
//  Created by Sylar on 2017/6/26.
//  Copyright © 2017年 ShiYun. All rights reserved.
//

#import "SN_PersonalInfo_ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "DateView.h"
#import "SN_EditUserNameViewController.h"

@interface SN_PersonalInfo_ViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate,UIActionSheetDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate,UIPickerViewDelegate,UIPickerViewDataSource>
{
    
    UIImageView *headImage;
    DateView * dateView;
    NSArray *sexArray;
    NSString *sexMark;
    NSInteger gender;
    NSString *birthdayDate;
    
    NSInteger sexSelectedIndex;
    
}

@property (nonatomic, strong) UITableView *infoTable;
@property (strong, nonatomic) UIImagePickerController *imagePicker;


@property(nonatomic,strong) UIPickerView *identityPicker;
@property(nonatomic,strong) UIControl *pickerBackView;
@property(nonatomic,strong) UIView *btnBackView;
@property(nonatomic,strong) UIButton *pickerSureBtn;


@end

@implementation SN_PersonalInfo_ViewController

- (void)loadView {
    
    [super loadView];
    
    self.navBar.navigationItem.title = @"个人信息";
    
    sexArray = [NSArray arrayWithObjects:@"男",@"女", nil];
    
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:YES];
    
    [self.infoTable reloadData];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    birthdayDate = [SYAccountTool ShareAccount].account.birthday;
    gender = [SYAccountTool ShareAccount].account.sex;
    
    NSString * convertStr = [NSString stringWithFormat:@"%d",[SYAccountTool ShareAccount].account.sex];
    if ([convertStr isEqualToString:@"0"]) {
        sexMark = @"男";
    }else if ([convertStr isEqualToString:@"1"]){
        sexMark = @"女";
    }else {
        sexMark = @"请选择";
    }
    
    [self.view addSubview:self.infoTable];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Request

- (void)editUserInfo {
    
    
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_user_edit" forKey:@"method"];
    [dict setObject:birthdayDate forKey:@"birthday"];
    [dict setObject:USERID forKey:@"userid"];
    [dict setObject:[SYAccountTool ShareAccount].account.username forKey:@"username"];
    [dict setObject:[NSString stringWithFormat:@"%ld",(long)gender] forKey:@"gender"];
    
    [Utils getWithparameters:dict showHUD:YES success:^(NSInteger recode, id jsonObject) {
        
        NSDictionary * dict = (NSDictionary *)jsonObject;
        NSDictionary * personalImformation = [dict objectForKey:@"re_data"];
        
        [self saveUserDataWithResposeData:personalImformation];
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
    
}

- (void)saveUserDataWithResposeData:(NSDictionary *)personalImformation
{
    BOOL save = [SyUserInfomation personalImformationSaveWtih:personalImformation];
    NSLog(@"save status 1 is success 0 is failture :%i",save);
    NSDictionary * userinfo = [personalImformation objectForKey:@"userinfo"];
    NSString * userID = [NSString stringWithFormat:@"%@",[userinfo objectForKey:@"userid"]];
    
    NSUserDefaults * UD = [NSUserDefaults standardUserDefaults];
    [UD setObject:userID forKey:@"userid"];
    [UD synchronize];
    
    [self.infoTable reloadData];

}

#pragma mark - TableViewDataSource && TableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 6;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        return 64;
    }else {
        return 44;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UILabel *titleLabel;
    UILabel *rightLabel;
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"cellIdentifier"];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(15, 43.5, SCREENWIDTH, 0.5)];
        [line setBackgroundColor:colorFromHex(@"#DEDEDE")];
        [cell.contentView addSubview:line];
        
        if (indexPath.row == 0) {
            
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            
            titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, 70, 64)];
            [titleLabel setFont:[UIFont systemFontOfSize:16]];
            titleLabel.textColor = colorFromHex(@"#979797");
            [cell.contentView addSubview:titleLabel];
            
            headImage = [[UIImageView alloc]initWithFrame:CGRectMake(SCREENWIDTH - 85, 9, 46, 46)];
            headImage.layer.cornerRadius = 23;
            headImage.clipsToBounds = YES;
            headImage.contentMode = UIViewContentModeScaleAspectFill;
            NSString *logo = [SYAccountTool ShareAccount].account.logo;
            if (![logo hasPrefix:@"http"]) {
                logo = [REQUESTIMAGEURL stringByAppendingString:logo];
            }
            [headImage sd_setImageWithURL:[NSURL URLWithString:logo] placeholderImage:[UIImage imageNamed:@"personalsettings_switchloading_pic_"]];
            [cell.contentView addSubview:headImage];
            
            [line setY:63.5];
            
        }else {
            
            titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 14, 170, 16)];
            [titleLabel setFont:[UIFont systemFontOfSize:16]];
            titleLabel.textColor = colorFromHex(@"#979797");
            [cell.contentView addSubview:titleLabel];
            
            if (indexPath.row == 3) {
                [line setX:0];
            }
        }
    }
    
    for (UIView *view in cell.contentView.subviews) {
        if (view.tag  > 50) {
            [view removeFromSuperview];
        }
    }
    
    rightLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREENWIDTH - 200, 14, 185, 16)];
    [rightLabel setFont:[UIFont systemFontOfSize:16]];
    rightLabel.tag = 51;
    rightLabel.textColor = colorFromHex(@"#3b3b3b");
    rightLabel.textAlignment = NSTextAlignmentRight;
    [cell.contentView addSubview:rightLabel];
    
    if (indexPath.row == 0) {
        titleLabel.text = @"头像";
    }else if (indexPath.row == 1) {
        titleLabel.text = @"姓名";
        rightLabel.text = [SYAccountTool ShareAccount].account.username;
    }else if (indexPath.row == 2) {
        
        titleLabel.text = @"生日";
        
        NSString *birthdayStr;
        if ([SYAccountTool ShareAccount].account.birthday.length > 10) {
            birthdayStr = [[SYAccountTool ShareAccount].account.birthday substringToIndex:10];
            rightLabel.text = birthdayStr;
        }else {
            rightLabel.text = @"待完善";
        }
        
        
    }else if (indexPath.row == 3) {
        
        titleLabel.text = @"师云号(邀请码)";
        
        rightLabel.text = [NSString stringWithFormat:@"%lld",[SYAccountTool ShareAccount].account.userid];
        
    }else if (indexPath.row == 4) {
        titleLabel.text = @"性别";
        
        if ([SYAccountTool ShareAccount].account.sex == 0) {
            rightLabel.text = @"男";
        }
        else if ([SYAccountTool ShareAccount].account.sex == 1) {
            rightLabel.text = @"女";
        }else {
            rightLabel.text = @"待完善";
        }
        
    }else if (indexPath.row == 5) {
        titleLabel.text = @"手机号";
        
        rightLabel.text = [SYAccountTool ShareAccount].account.mobile;
        
    }else if (indexPath.row == 6) {
        
        titleLabel.text = @"身份证号";
        
        rightLabel.text = [NSString stringWithFormat:@"%ld",[SYAccountTool ShareAccount].account.cardid];
        
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"照相机",@"相册", nil];
        [actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
    }else if (indexPath.row == 1) {//用户名
        SN_EditUserNameViewController *VC = [[SN_EditUserNameViewController alloc]init];
        [self.navigationController pushViewController:VC animated:YES];
    }else if (indexPath.row == 2) {//生日
        [dateView removeFromSuperview];
        
        dateView = [[DateView alloc] initAddSuperView:self.view];
        [dateView.datePicker setMaximumDate:[NSDate date]];
        __weak SN_PersonalInfo_ViewController *weakSelf = self;
        
        dateView.getDate = ^(NSString *dateStr){
            
            SN_PersonalInfo_ViewController* strongSelf = weakSelf;
            NSMutableString * dateS = [NSMutableString stringWithFormat:@"%@",dateStr];
            birthdayDate = [[dateS componentsSeparatedByString:@" "]firstObject];
            
            [strongSelf editUserInfo];
            
        };
    }else if (indexPath.row == 4) {//性别
        UIWindow * window = KeyWindow;
        [window addSubview:self.pickerBackView];
    }
}
#pragma mark -UIPickerViewDataSource && UIPickerViewDelegate
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    
    return 1;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    
    return 2;
}

-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    
    NSString * str = [sexArray objectAtIndex:row];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 20)];
    label.text = str;
    label.textAlignment = NSTextAlignmentCenter;
    return label;
    
}

-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    
    return 44;
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    sexSelectedIndex = row;
    //sexMark = [sexArray objectAtIndex:row];
}

#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        NSString *mediaType = AVMediaTypeVideo;
        
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        
        
        if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
            
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的“设置－隐私－相机”中允许访问相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            alert.tag=201;
            [alert show];
            
        }else
        {
#if TARGET_IPHONE_SIMULATOR
            [self showHint:NSLocalizedString(@"message.simulatorNotSupportCamera", @"simulator does not support taking picture")];
#elif TARGET_OS_IPHONE
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
                    _imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
                }
                self.imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
                [self presentViewController:self.imagePicker animated:YES completion:NULL];
            } else {
                
            }
#endif
        }
    } else if (buttonIndex == 1) {
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        self.imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
        [self presentViewController:self.imagePicker animated:YES completion:NULL];
        
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self hideHud];
    [self showHudInView:self.view hint:@"正在上传"];
    
    //获取的照片是编辑以后的照片
    //UIImage *orgImage = info[UIImagePickerControllerEditedImage];
    UIImage *editImage = [info objectForKey:UIImagePickerControllerEditedImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    if (editImage) {
        NSData * fileData = UIImageJPEGRepresentation(editImage, 0.5);
        
        NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
        [dict setObject:@"InsertfileInfo" forKey:@"method"];
        [dict setObject:@"1" forKey:@"typeid"];
        [dict setObject:[fileData base64Encoding] forKey:@"file"];
        [dict setObject:@"11" forKey:@"filename"];
        [dict setObject:@"file" forKey:@"description"];
        [dict setObject:@".jpg" forKey:@"kz"];
        dict  = [Utils completeImageSubmitParameterWith:dict];
        NSString * postValue = [Utils getXMLStringWithParameter:dict];
        
        __weak typeof(self) weakSelf = self;
        
        [Utils submitImageToWebService:SUBMITIMAGEURL SOAPActionSring:@"http://tempuri.org/InsertfileInfo" postValue:postValue success:^(NSInteger recode, id resposeJson){
            
            NSDictionary * dict = (NSDictionary *)resposeJson;
            NSString * returncode = [dict objectForKey:@"returncode"];
            if ([returncode isEqualToString:@"10000"]) {
                NSString * url = [dict objectForKey:@"url"];
                
                [Utils resaePersonadataWithLogo:url];
                
                [weakSelf editImformationWithImageURL:url];
                url=[NSString stringWithFormat:@"%@%@",REQUESTIMAGEURL,url];
                [self->headImage sd_setImageWithURL:[NSURL URLWithString:url]];
                
                [weakSelf hideHud];
            }
            
            
        } failure:^(NSInteger recode, NSError * error){
            [self hideHud];
            [self showHint:@"上传失败"];
        }];
        
        
    }
}




- (void)editImformationWithImageURL:(NSString *)imageurlStr
{
    if (imageurlStr.length == 0)
        return;
    
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_userlogo_edit" forKey:@"method"];
    [dict setObject:imageurlStr forKey:@"logo"];
    [dict setObject:USERID forKey:@"userid"];
    [Utils getWithparameters:dict showHUD:YES success:^(NSInteger recode, id jsonObject) {
        [self hideHud];
        [self showHint:@"头像修改成功"];
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
    
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
}

-(UIControl *)pickerBackView{
    
    if (_pickerBackView == nil) {
        
        _pickerBackView = [[UIControl alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGH)];
        _pickerBackView.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"toumingbg"]];
        [_pickerBackView addTarget:self action:@selector(canclePickerACtion) forControlEvents:UIControlEventTouchUpInside];
        
        _btnBackView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREENHEIGH-210, SCREENWIDTH, 210)];
        _btnBackView.backgroundColor = [UIColor whiteColor];
        
        
        _pickerSureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _pickerSureBtn.frame = CGRectMake(SCREENWIDTH-15-40, 10, 40, 17);
        [_pickerSureBtn setTitle:@"完成" forState:UIControlStateNormal];
        _pickerSureBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_pickerSureBtn setTitleColor:RGBCOLOR(57, 173, 255) forState:UIControlStateNormal];
        [_pickerSureBtn addTarget:self action:@selector(chooseTypeAndCancelPicker:) forControlEvents:UIControlEventTouchUpInside];
        [_btnBackView addSubview:_pickerSureBtn];
        
        _identityPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0,37, VIEW_WIDTH, 173)];
        _identityPicker.dataSource = self;
        _identityPicker.delegate = self;
        _identityPicker.backgroundColor = [UIColor whiteColor];
        
        if ([sexMark isEqualToString:@"女"]) {
            
            [_identityPicker selectRow:1 inComponent:0 animated:NO];
            
        }else
        {
            [_identityPicker selectRow:0 inComponent:0 animated:NO];
        }
        
        [_btnBackView addSubview:_identityPicker];
        
        [_pickerBackView addSubview:_btnBackView];
        
        
    }
    
    return _pickerBackView;
}

- (void)canclePickerACtion {
    
    [self.pickerBackView removeFromSuperview];
}

- (void)chooseTypeAndCancelPicker:(UIButton *)sender {
    
    sexMark = [sexArray objectAtIndex:sexSelectedIndex];
    
    if (!sexMark) {
        sexMark = @"男";
    }
    
    if ([sexMark isEqualToString:@"男"]) {
        sexMark=@"0";
        gender = 0;
    }else if ([sexMark isEqualToString:@"女"])
    {
        sexMark=@"1";
        gender = 1;
    }
    [self.pickerBackView removeFromSuperview];
    
    [self editUserInfo];
    
}

#pragma mark - Get

- (UITableView *)infoTable {
    
    if (_infoTable == nil) {
        _infoTable = [[UITableView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH - SafeAreaTopHeight) style:(UITableViewStylePlain)];
        _infoTable.delegate = self;
        _infoTable.dataSource = self;
        _infoTable.scrollEnabled = NO;
        _infoTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _infoTable;
}

- (UIImagePickerController *)imagePicker
{
    if (_imagePicker == nil) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.modalPresentationStyle= UIModalPresentationPageSheet;
        _imagePicker.allowsEditing = YES;
        _imagePicker.delegate = self;
    }
    
    return _imagePicker;
}

@end
